package com.qf.realm;

import com.qf.domain.SysUsers;
import com.qf.service.SysMenuService;
import com.qf.service.SysRoleService;
import com.qf.service.SysUsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    SysUsersService usersService;

    @Autowired
    SysRoleService roleService;

    @Autowired
    SysMenuService menuService;
//授权：获取权限和角色
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUsers user = (SysUsers) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //从数据库查询 当前用户的角色信息
        Set<String> roles = roleService.findRolesByUserId(user.getId());
        //设置角色
        authorizationInfo.setRoles(roles);
        //从数据库查询当前用户的权限信息
        Set<String> stringPermissions = menuService.findPermsByUserId(user.getId());
        //设置权限
        authorizationInfo.setStringPermissions(stringPermissions);

        return authorizationInfo;
    }
//认证：
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//从token中获取用户名
        String username = (String) token.getPrincipal();
        //从token中获取密码
        String password =  new String((char[]) token.getCredentials());

        //根据用户名 查询数据库 中用户信息
        SysUsers user = usersService.findByUsername(username);
        //校验（用户信息）
        //如果user为空，说明没有用户
        if(user == null) {
            throw new UnknownAccountException("未知的账户");
        }
        if(user.getStatus() == 0) {
            throw new LockedAccountException("账户已锁定");
        }
        //user.getPassword() 从数据库中查询到密码
        //对用户输入的密码进行加密，迭代加密 1024次
        Md5Hash md5 = new Md5Hash(password,username , 1024);
        //如果密码为空，或者密码不同，说明密码不正确
        if(user.getPassword() == null || !user.getPassword().equals(md5.toString())) {
            throw new CredentialsException("密码不正确");
        }
        //创建返回值对象
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, user.getRealname());

        return authenticationInfo;
    }
}
